package com.conversationboard.controller;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.conversationboard.config.Configuration;
import com.conversationboard.controller.debug.ServletDebugInfo;
import com.conversationboard.email.Mail;
import com.conversationboard.logger.Logger;
import com.conversationboard.model.PendingRegistration;
import com.conversationboard.model.PendingRegistrations;
import com.conversationboard.model.User;
import com.conversationboard.security.EncryptedKey;
import com.conversationboard.security.EncryptionException;

@WebServlet(name = "AdminPendingRegistrationsControllerServlet", urlPatterns = "/Admin/AdminPendingRegistrationsControllerServlet")
public class AdminPendingRegistrationsControllerServlet extends HttpServlet {

	private static final long serialVersionUID = 2330468236909088984L;


	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");

		try {

			if (!Configuration.getInstance().isAllowBlockRegistration()) {
				return;
			}

			/* Are you authorised? */

			User user = User.get(request.getUserPrincipal().getName());

			if (!user.isSiteAdmin()) {
				return;
			}

			String key = request.getParameter("key");
			EncryptedKey encryptedKey = new EncryptedKey();

			if (!encryptedKey.isValid(key, user.getLoginId())) {
				Logger.log(new Date(), "Part 1 of error: " + this.getClass().getName(), user);
				String postRequest = ServletDebugInfo.getRawRequest(request);
				Logger.log(new Date(), "Part 2 of error:\n\n" + postRequest, user);
				return;
			}

			/* Iterate through parameters to accept/deny registrations */

			PendingRegistrations pendingRegistrations = PendingRegistrations.getInstance();

			/* The input parameters are keyed by login ID */

			List<PendingRegistration> removalList = new LinkedList<PendingRegistration>();
			List<String> failedRegistrations = new LinkedList<String>();

			for (PendingRegistration pendingRegistration : pendingRegistrations) {

				String parameter = request.getParameter(pendingRegistration.getLoginId());

				if (parameter == null) {
					continue;
				}

				if (parameter.equalsIgnoreCase("accept")) {

					/*
					 * Make sure that no individual failed registration prevents
					 * further registrations: catch Throwable and dump to sysout
					 * for debug.
					 */

					try {
						User.add(pendingRegistration.getDisplayName(), pendingRegistration.getLoginId(), pendingRegistration.getDisplayName(), pendingRegistration.getHash(),
								pendingRegistration.getTimeZone(), pendingRegistration.getIpAddress());

						Mail mail = new Mail();
						mail.send("noreply@pleasedonotreplytothisemail.com", pendingRegistration.getLoginId(), "Successful Registration", "Thankyou for registering. Your password is: "
								+ pendingRegistration.getPassword() + "\n\nIf you wish, you may <a href='" + Configuration.getInstance().getDomainName() + "/" + Configuration.getInstance().getRoot()
								+ "/changepassword.jsp'>change your password here</a>.");

						removalList.add(pendingRegistration);

					} catch (Throwable t) {
						failedRegistrations.add(pendingRegistration.getLoginId());
						t.printStackTrace();
					}

				} else if (parameter.equalsIgnoreCase("reject")) {
					removalList.add(pendingRegistration);
				}

			}

			for (PendingRegistration pendingReg : removalList) {
				pendingRegistrations.remove(pendingReg);
			}

			pendingRegistrations.store();

			if (!failedRegistrations.isEmpty()) {

				String message = "The following registrations failed:";

				for (String loginId : failedRegistrations) {
					message = message + "<p>" + loginId + "</p>";
				}

				RequestDispatcher dispatcher = request.getRequestDispatcher("/Pages/messagepage.jsp");
				request.setAttribute("message", message);
				dispatcher.forward(request, response);
				return;
			}

			response.sendRedirect(Configuration.getInstance().getRoot() + "/index.jsp");

		} catch (SQLException e) {
			throw new ServletException(e);
		} catch (EncryptionException e) {
			throw new ServletException(e);
		}

	}
}
